<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stomp</title>
</head>
<body>
<span id="message"></span><br/>
<span id="login-user"></span><br/>
<input id="login-name" type="text"/><button type="button" onclick="login()">登录</button><br/>
<button id="connect" type="button" onclick="connect()">连接</button><br/>
<button id="disconnect" type="button" disabled="disabled" onclick="disconnect()">断开</button><br/>
<input id="text-value" type="text"/><button type="button" onclick="send()">发送</button><br/>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script>
    let ws;
    let stompClient;

    function login() {
        let loginName = $("#login-name").val();
        if (_.isEmpty(loginName)) {
            $("#message").html("登录名不能为空");
            return;
        }
        $.post("http://127.0.0.1:8080/login", {name:loginName}, function (resp) {
            $("#message").html("登录成功");
            $.get("http://127.0.0.1:8080/loginUser", function (resp) {
                $("#login-user").html(resp);
            })
        }, "text");
    }

    function send() {
        $.ajax({
            type: "post",
            url: "/sendRoomMessage",
            contentType: "application/json",
            data: $("#text-value").val(),
            success: function (resp) {
                $("#message").html("发送成功");
            }
        })
    }

    function connect() {
        ws = new SockJS("http://127.0.0.1:8080/stompEndpoint");
        stompClient = Stomp.over(ws);
        stompClient.heartbeat.outgoing = 20000;
        stompClient.heartbeat.incoming = 0;
        stompClient.connect(
            {},
            function (resp) {
                console.log('Connected: ' + resp);
                $("#connect").attr("disabled", "disabled");
                $("#disconnect").removeAttr("disabled");
                stompClient.subscribe('/topic/roomMessage', function (message) {
                    $("body").append("<span>" + message.body + "</span><br/>")
                });
                let username = $("#login-user").html();
                stompClient.send("/app/joinRoom", {}, username);
            },
            function (resp) {
                console.log('Error: ' + resp);
                $("#connect").removeAttr("disabled");
                $("#disconnect").attr("disabled", "disabled");
            }
        );
    }

    function disconnect() {
        stompClient.disconnect(function() {
            console.log('Disconnected');
            $("#connect").removeAttr("disabled");
            $("#disconnect").attr("disabled", "disabled");
        });
    }
</script>
</body>
</html>